// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || [];
    logs.unshift(Date.now());
    wx.setStorageSync('logs', logs);

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    });

    // 初始化蓝牙功能
    this.bleInit();
  },

  globalData: {
    userInfo: null,
    ble: {
      deviceId: '',
      serviceId: '',
      characteristicId: '',
      deviceName: ''  // 设备名称
    },
    circleRadius: 1000 // 默认范围大小，单位为米
  },

  // 蓝牙初始化
  bleInit() {
    console.log('开始搜索蓝牙设备');
    
    // 监听扫描到新设备的事件
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach((device) => {
        // 这里可以根据需要做设备过滤
        console.log('设备发现:', device);
        if (device.deviceId == "D8:3B:DA:40:06:61") {
          // 找到目标设备，开始连接
          this.bleConnection(device.deviceId);
          wx.stopBluetoothDevicesDiscovery();  // 停止蓝牙扫描
        }
      });
    });

    // 初始化蓝牙模块
    wx.openBluetoothAdapter({
      mode: 'central',
      success: (res) => {
        // 开始搜索附近的蓝牙外围设备
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
        });
      },
      fail: (res) => {
        if (res.errCode !== 10001) return;
        // 蓝牙不可用时，监听状态变化
        wx.onBluetoothAdapterStateChange((res) => {
          if (!res.available) return;
          wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false,
          });
        });
      }
    });

    // 监听特征值变化
    wx.onBLECharacteristicValueChange((result) => {
      console.log('onBLECharacteristicValueChange', result.value);
      let hex = this.ab2hex(result.value);  // 转换为十六进制字符串
      console.log('hex:', hex);

      // 解析GPS坐标
      let gpsData = this.hextoString(hex);
      if (gpsData.startsWith('ID')) {
        gpsData = gpsData.substring(5); // 从第6个字符开始，前面为"IDxx:"
      }
      let gpsParts = gpsData.split(',');
      if (gpsParts.length === 2) {
        let latitude = parseFloat(gpsParts[0].replace('N', '')); // 解析纬度
        let longitude = parseFloat(gpsParts[1].replace('E', '')); // 解析经度
        console.log('解析GPS:', latitude, longitude);

        // 跳转到地图页面并传递经纬度和设备名称
        wx.navigateTo({
          url: `/pages/map/map?latitude=${latitude}&longitude=${longitude}&deviceName=${this.globalData.ble.deviceName || '设备'}` 
        });
      }
    });
  },

  // 蓝牙设备连接
  bleConnection(deviceId) {
    wx.createBLEConnection({
      deviceId, // 搜索到设备的deviceId
      success: () => {
        // 连接成功，获取设备服务
        console.log('连接成功，获取服务');
        wx.setBLEMTU({
          deviceId: deviceId,
          mtu: 40, // 设置 MTU 大小（建议设置为 100 或更大）
          success: (res) => {
            console.log('MTU 设置成功:', res.mtu);
          },
          fail: (res) => {
            console.error('MTU 设置失败:', res);
          }
        });
        this.bleGetDeviceServices(deviceId);
      }
    });
  },

  // 获取蓝牙设备服务
  bleGetDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log('服务列表:', res.services);
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            // 选择主服务进行通信
            this.bleGetDeviceCharacteristics(deviceId, res.services[i].uuid);
          }
        }
      }
    });
  },

  // 获取设备特征值
  bleGetDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i];
          console.log(item);
          if (item.properties.write) { // 可写特征值
            // 向设备发送指令，例如“getid”
            var buffer = this.stringToBytes("getid");
            this.globalData.ble.deviceId = deviceId;
            this.globalData.ble.serviceId = serviceId;
            this.globalData.ble.characteristicId = item.uuid;
            wx.writeBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              value: buffer,
            });
          }
          if (item.properties.read) { // 可读特征值
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            });
          }
          if (item.properties.notify || item.properties.indicate) {
            // 启用通知特性
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            });
          }
        }
      }
    });
  },

  // 字符串转字节数组
  stringToBytes(str) {
    var array = new Uint8Array(str.length);
    for (var i = 0, l = str.length; i < l; i++) {
      array[i] = str.charCodeAt(i);
    }
    console.log(array);
    return array.buffer;
  },

  // 十六进制字符串转普通字符串
  hextoString(hex) {
    var arr = hex.split("");
    var out = "";
    for (var i = 0; i < arr.length / 2; i++) {
      var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1];
      var charValue = String.fromCharCode(parseInt(tmp, 16));  // 修正：正确转换为字符
      out += charValue;
    }
    return out;
  },

  // ArrayBuffer 转十六进制字符串
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join('');
  },

  // 设置设备名称
  setDeviceName(name) {
    this.globalData.ble.deviceName = name;
  },

  // 设置范围大小
  setCircleRadius(newRadius) {
    this.globalData.circleRadius = newRadius;
  },

  // 获取范围大小
  getCircleRadius() {
    return this.globalData.circleRadius;
  }
});